﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;
using ReAnimation.Infrastructure.Services.DomainFactories.Interfaces;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ReAnimation.Domain.Services
{
    public class AnimationStoreService: IAnimationStoreService
    {
        private IAnimationFactory _animationFactory;
        
        public AnimationStoreService(IAnimationFactory animationFactory)
        {
            _animationFactory = animationFactory;
        }

        #region IAnimationStoreService Members

        public bool SaveToFile(Animation animation, string filePath)
        {
            if(animation == null) return false;
            if (String.IsNullOrEmpty(filePath)) return false;

            Stream stream = new FileStream(filePath, FileMode.Create);

            if (!stream.CanRead) return false;

            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(stream, animation);

            stream.Close();
            return true;
        }

        public Animation ReadFromFile(string filePath)
        {
            if (String.IsNullOrEmpty(filePath)) return null;

            Stream stream = new FileStream(filePath, FileMode.Open);
            BinaryFormatter bf = new BinaryFormatter();
            Animation animation = null;
            try
            {
                animation = bf.Deserialize(stream) as Animation;
            }
            catch(Exception e)
            {
                return null;
            }
            if (animation == null) return null;

            return _animationFactory.CloneAnimation(animation);
        }

        #endregion
    }
}
